package Thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyBlockingQueue{
     private String[] data;
     private int head=0;
     private int tail=0;
     private int size=0;
     //手动创建锁
     private Object locker=new Object();

     private MyBlockingQueue(int capacity){
         data=new String[capacity];
     }
     public void put(String elem) throws InterruptedException {
         synchronized (locker){
             //使用while比使用if更好
             while (size== data.length){
                 //满了,阻塞，等到不满再唤醒
                 locker.wait();
             }
             data[tail]=elem;
             tail++;
             if (tail>= data.length){
                 tail=0;
             }
             size++;
             locker.notify();
         }
     }
     public String take() throws InterruptedException {
         synchronized (locker){
             //使用while比使用if更好
             while (size==0){
                 //空的，阻塞，等到不空再唤醒
                 locker.wait();
             }
             String elem=data[head];
             head++;
             if (head> data.length){
                 head=0;
             }
             size--;
             locker.notify();
             return elem;
         }
     }
 }
public class Demo11 {
    public static void main(String[] args) {
        BlockingQueue<Long> queue=new ArrayBlockingQueue<>(1000);
        //生产者
        Thread t1=new Thread(()->{
            long n=0;
            while (true){
                try {
                    queue.put(n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产了"+n);
                n++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //消费者
        Thread t2=new Thread(()->{
            while (true){
                try {
                    Long n = queue.take();
                    System.out.println("消费了"+n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
